<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2007/03/22 11:30:51 $)
// $RCSfile: functions_parser.php,v $ : $Revision: 1.12 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* View the Parser Log
*/
function viewParserLog($parserlogid, $ticketpostid = false)
{
	global $dbCore, $_SWIFT, $template;

	if ($parserlogid)
	{
		$_parserlog = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."parserlogs` AS parserlogs LEFT JOIN `". TABLE_PREFIX ."parserlogdata` AS parserlogdata ON (parserlogs.parserlogid = parserlogdata.parserlogid) WHERE parserlogs.parserlogid = '". intval($parserlogid) ."';");
	} else if ($ticketpostid) {
		$_parserlog = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."parserlogs` AS parserlogs LEFT JOIN `". TABLE_PREFIX ."parserlogdata` AS parserlogdata ON (parserlogs.parserlogid = parserlogdata.parserlogid) WHERE parserlogs.ticketpostid = '". intval($ticketpostid) ."';");
	}

	if (empty($_parserlog["parserlogid"]))
	{
		echo $template->displayTemplate("header.tpl");
		echo '<span class="mediumtext">'.$_SWIFT["language"]["invalidparserlog"].'</span>';
		echo $template->displayTemplate("footer.tpl");
		exit;
	}
	$_mime = unserialize($_parserlog["contents"]);

	$template->assign("documenttitle", $_SWIFT["language"]["viewparserlog"]);
	echo $template->displayTemplate("header.tpl");
	echo '<body>';
	printFormStart();

	printMainTableHeader(sprintf($_SWIFT["language"]["parserlogentry"], $_parserlog["parserlogid"]), "650");

	$infolist = $colarray = array();
	$infolist[] = array($_SWIFT["language"]["pparserlogid"], htmlspecialchars($_parserlog["parserlogid"]));
	$infolist[] = array($_SWIFT["language"]["ppticketid"], intval($_parserlog["typeid"]));
	$infolist[] = array($_SWIFT["language"]["ppticketmaskid"], htmlspecialchars($_parserlog["ticketmaskid"]));
	$infolist[] = array($_SWIFT["language"]["ppdate"], edate($_SWIFT["settings"]["dt_datetimeformat"], $_parserlog["dateline"]));
	$infolist[] = array($_SWIFT["language"]["pptimeline"], varDate(DATENOW-$_parserlog["dateline"]));
	$infolist[] = array($_SWIFT["language"]["ppemailqueue"], htmlspecialchars($_SWIFT["queuecache"]["list"][$_parserlog["emailqueueid"]]["email"]));
	$infolist[] = array($_SWIFT["language"]["ppstatus"], iif($_parserlog["logtype"]=="success", '<img src="'. $_SWIFT["themepath"] .'icon_success.gif" border="0" align="absmiddle" />&nbsp;'.$_SWIFT["language"]["success"], '<img src="'. $_SWIFT["themepath"] .'icon_failure.gif" border="0" align="absmiddle" />&nbsp;'.$_SWIFT["language"]["failure"]));
	$infolist[] = array($_SWIFT["language"]["ppsubject"], htmlspecialchars($_parserlog["subject"]));
	$infolist[] = array($_SWIFT["language"]["ppfromemail"], htmlspecialchars($_parserlog["fromemail"]));
	$infolist[] = array($_SWIFT["language"]["pptoemail"], htmlspecialchars($_parserlog["toemail"]));
	$infolist[] = array($_SWIFT["language"]["ppsize"], formattedSize($_parserlog["size"]));
	$infolist[] = array($_SWIFT["language"]["pptimetaken"], number_format($_parserlog["parsetimetaken"], 3)."&nbsp;".$_SWIFT["language"]["seconds"]);

	printDescRow($_SWIFT["language"]["generalinformation"], 4);
	$cnt = $index = 0;
	$lastindex = count($infolist)-1;
	for ($ii=0; $ii<count($infolist); $ii++)
	{
		$colarray[$index]["align"] = "left";
		$colarray[$index]["valign"] = "top";
		$colarray[$index]["nowrap"] = true;
		$colarray[$index]["value"] = $infolist[$ii][0];
		$colarray[$index]["class"] = "row1";
		$index++;
		$colarray[$index]["align"] = "left";
		$colarray[$index]["valign"] = "top";
		$colarray[$index]["nowrap"] = true;
		$colarray[$index]["value"] = $infolist[$ii][1];
		$colarray[$index]["class"] = "row2";
		$cnt++; $index++;

		if ($cnt == 2 || $ii == $lastindex)
		{
			printDataRow($colarray);
			$colarray = array();
			$index = 0;
			$cnt=0;
		}
	}

	printDescRow($_SWIFT["language"]["ppresult"], 4);

	$data = array();
	$data[0]["value"] = '<span class="smalltext">'. htmlspecialchars($_parserlog["description"]) .'</span>'.SWIFT_CRLF;
	$data[0]["align"] = "left";
	$data[0]["colspan"] = "4";
	printDataRow($data);

	printDescRow($_SWIFT["language"]["mimedata"], 4);
	$colarray = array();
	$colarray[0]["align"] = "left";
	$colarray[0]["valign"] = "top";
	$colarray[0]["colspan"] = "4";
	$colarray[0]["nowrap"] = true;
	$colarray[0]["value"] = '<textarea style="WIDTH:640px;" name="contents" cols="50" rows="18">'. htmlspecialchars($_mime["mimedata"]) .'</textarea>'.SWIFT_CRLF;
	$colarray[0]["class"] = "row1";
	printDataRow($colarray);

	if ($_mime["mimedata"] != $_SWIFT["language"]["clearedduelimit"] && !empty($_mime["mimedata"]))
	{
		printSubmitRow($_SWIFT["language"]["reprocessemail"], "4");
	}

	addHiddenField("_m", "parser");
	addHiddenField("_a", "viewparserlog");
	addHiddenField("step", "1");
	addHiddenField("parserlogid", intval($_REQUEST["parserlogid"]));
	printMainTableFooter();
	printFormEnd();
	echo '</body>';

	echo $template->displayTemplate("footer.tpl");
}

/**
* Update Existing Email Queue
*/
function updateQueue($emailqueueid, $email, $tgroupid, $departmentid, $priorityid, $ticketstatusid, $type = MODULE_TICKETS, $fetchtype = "pipe", $host = "", $port = "", $username = "", $password = "", $customfromname = "", $customfromemail = "", $queuesignature = "", $registrationrequired = false, $issueautoresponder = true, $replyautoresponder = false, $prefix)
{
	global $dbCore, $_SWIFT;

	$issueautoresponder = iif($issueautoresponder==true, "1", "0");
	$registrationrequired = iif($registrationrequired==true, "1", "0");
	$replyautoresponder = iif($replyautoresponder==true, "1", "0");

	$dbCore->query("UPDATE `". TABLE_PREFIX ."emailqueues` SET `email` = '". $dbCore->escape($email) ."', `type` = '". $dbCore->escape($type) ."', `fetchtype` = '". $dbCore->escape($fetchtype) ."', `host` = '". $dbCore->escape($host) ."', `port` = '". $dbCore->escape($port) ."', `username` = '". $dbCore->escape($username) ."', `userpassword` = '". $dbCore->escape($password) ."', `customfromname` = '". $dbCore->escape($customfromname) ."', `customfromemail` = '". $dbCore->escape($customfromemail) ."', `priorityid` = '". $dbCore->escape($priorityid) ."', `ticketstatusid` = '". $dbCore->escape($ticketstatusid) ."', `departmentid` = '". $dbCore->escape($departmentid) ."', `prefix` = '". $dbCore->escape($prefix) ."', `ticketautoresponder` = '". $dbCore->escape($issueautoresponder) ."', `replyautoresponder` = '". $dbCore->escape($replyautoresponder) ."', `registrationrequired` = '". $dbCore->escape($registrationrequired) ."', `tgroupid` = '". intval($tgroupid) ."' WHERE `emailqueueid` = '". intval($emailqueueid) ."';");

	$dbCore->query("UPDATE `". TABLE_PREFIX ."queuesignatures` SET `contents` = '". $dbCore->escape($queuesignature) ."' WHERE `emailqueueid` = '". intval($emailqueueid) ."';");

	rebuildQueueCache();

	return true;
}

/**
* Inserts a new Email Queue
*/
function insertQueue($email, $tgroupid, $departmentid, $priorityid, $ticketstatusid, $type = MODULE_TICKETS, $fetchtype = "pipe", $host = "", $port = "", $username = "", $password = "", $customfromname = "", $customfromemail = "", $queuesignature = "", $registrationrequired = false, $issueautoresponder = true, $replyautoresponder = false, $prefix)
{
	global $dbCore, $_SWIFT;

	$issueautoresponder = iif($issueautoresponder==true, "1", "0");
	$registrationrequired = iif($registrationrequired==true, "1", "0");
	$replyautoresponder = iif($replyautoresponder==true, "1", "0");

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."emailqueues` (`email`, `type`, `fetchtype`, `host`, `port`, `username`, `userpassword`, `customfromname`, `customfromemail`, `priorityid`, `ticketstatusid`, `departmentid`, `prefix`, `ticketautoresponder`, `replyautoresponder`, `registrationrequired`, `tgroupid`) VALUES ('". $dbCore->escape($email) ."', '". $dbCore->escape($type) ."', '". $dbCore->escape($fetchtype) ."', '". $dbCore->escape($host) ."', '". $dbCore->escape($port) ."', '". $dbCore->escape($username) ."', '". $dbCore->escape($password) ."', '". $dbCore->escape($customfromname) ."', '". $dbCore->escape($customfromemail) ."', '". $dbCore->escape($priorityid) ."', '". $dbCore->escape($ticketstatusid) ."', '". $dbCore->escape($departmentid) ."', '". $dbCore->escape($prefix) ."', '". $dbCore->escape($issueautoresponder) ."', '". $dbCore->escape($replyautoresponder) ."', '". $dbCore->escape($registrationrequired) ."', '". intval($tgroupid) ."');");

	$emailqueueid = $dbCore->lastInsertId();

	// Do we need to insert the signature?
	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."queuesignatures` (`dateline`, `emailqueueid`, `contents`) VALUES ('". DATENOW ."', '". $dbCore->escape($emailqueueid) ."', '". $dbCore->escape($queuesignature) ."');");

	rebuildQueueCache();

	return $emailqueueid;
}

/**
* Delete the specified parserlogs
*/
function deleteParserLogs($parserlogidlist)
{
	global $dbCore;

	if (!_is_array($parserlogidlist))
	{
		return false;
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."parserlogs` WHERE `parserlogid` IN (". buildIN($parserlogidlist) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."parserlogdata` WHERE `parserlogid` IN (". buildIN($parserlogidlist) .");");

	return true;
}

/**
* Rebuilds the Email Queue Cache
*/
function rebuildQueueCache()
{
	global $dbCore, $_SWIFT, $datastore;

	$queuecache = array();

	$dbCore->query("SELECT *, emailqueues.emailqueueid AS demailqueueid FROM `". TABLE_PREFIX ."emailqueues` AS emailqueues LEFT JOIN `". TABLE_PREFIX ."queuesignatures` AS queuesignatures ON (emailqueues.emailqueueid = queuesignatures.emailqueueid) ORDER BY emailqueues.emailqueueid ASC;");
	while ($dbCore->nextRecord())
	{
		$queuecache["p"][$dbCore->Record["email"]] = $dbCore->Record["demailqueueid"];

		$drecord = array();
		foreach ($dbCore->Record as $key=>$val)
		{
			if (!empty($val))
			{
				$drecord[$key] = $val;
			}
		}
		$queuecache["list"][$dbCore->Record["demailqueueid"]] = $drecord;
		$queuecache["list"][$dbCore->Record["demailqueueid"]]["emailqueueid"] = $dbCore->Record["demailqueueid"];
		unset($queuecache["list"][$dbCore->Record["demailqueueid"]]["type"]);
		unset($queuecache["list"][$dbCore->Record["demailqueueid"]]["dateline"]);
		unset($queuecache["list"][$dbCore->Record["demailqueueid"]]["demailqueueid"]);
	}

	$datastore->update("queuecache", $queuecache);
}

/**
* Deletes all queues with the given email queue id array
*/
function deleteQueues($emailqueueidarray)
{
	global $dbCore, $_SWIFT;

	if (!is_array($emailqueueidarray) || count($emailqueueidarray) == 0)
	{
		return false;
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."emailqueues` WHERE `emailqueueid` IN (". buildIN($emailqueueidarray) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."queuesignatures` WHERE `emailqueueid` IN (". buildIN($emailqueueidarray) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."catchallrules` WHERE `emailqueueid` IN (". buildIN($emailqueueidarray) .");");

	rebuildQueueCache();

	return true;
}

/**
* Insert a new breakline
*/
function insertBreakline($breakline)
{
	global $dbCore;

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."breaklines` (`breakline`) VALUES ('". $dbCore->escape($breakline) ."');");

	rebuildBreakLineCache();

	return true;
}

/**
* Deletes breaklines
*/
function deleteBreaklines($breaklineidarray)
{
	global $dbCore;

	if (!_is_array($breaklineidarray))
	{
		return false;
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."breaklines` WHERE `breaklineid` IN (". buildIN($breaklineidarray) .");");

	rebuildBreakLineCache();

	return true;
}

/**
* Rebuilds the Break Lines Cache
*/
function rebuildBreakLineCache()
{
	global $dbCore, $datastore;

	$breaklinecache = array();

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."breaklines` ORDER BY `breaklineid` ASC;");
	while ($dbCore->nextRecord())
	{
		$breaklinecache[] = $dbCore->Record["breakline"];
	}

	$datastore->update("breaklinecache", $breaklinecache);		
}
?>